package com.yxj.lib_exo;

import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class HorizontalLoadingView extends LinearLayout {

    private View v;

    public HorizontalLoadingView(Context context) {
        this(context, null);
    }

    public HorizontalLoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HorizontalLoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        addView(v = LayoutInflater.from(context).inflate(R.layout.hor_loading_layout, this, false));
    }

    /**
     * @param p
     */
    private void setProgress(int p) {
        ((ProgressBar) v.findViewById(R.id.pBar1)).setProgress(p);
        ((ProgressBar) v.findViewById(R.id.pBar2)).setProgress(p);
    }


    /**
     * 重复的线性动画
     */
    private ValueAnimator valueAnimator;
    private void start() {
        valueAnimator = ValueAnimator.ofFloat(0.1f, 1f);
        valueAnimator.setRepeatCount(-1);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.setDuration(400);
        valueAnimator.start();
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(@NonNull ValueAnimator animation) {
                float f = (float) animation.getAnimatedValue();
                int p = (int) (f * 10000);
                setProgress(p);
            }
        });
    }


    private void stop() {
        if (valueAnimator != null) {
            valueAnimator.cancel();
            valueAnimator.reverse();
            valueAnimator = null;
        }
    }


    public void loading(boolean isLoading) {
        setVisibility(isLoading? View.VISIBLE : GONE);
        if (isLoading){
            start();
        }else {
            stop();
        }
    }
}
